import pymysql

# 连接数据库，关闭自动提交
conn = pymysql.connect(
    host='192.168.203.100',
    port=3306,
    user='root',
    password='root',
    database='lianxi',
    charset='utf8mb4',
    autocommit=False  # 关闭自动提交
)

cursor = conn.cursor()

try:
    # 操作 1：查询数据
    cursor.execute('SELECT * FROM tb_user')
    results = cursor.fetchall()
    for row in results:
        print(row)

    # 操作 2：插入数据
    # cursor.execute("INSERT INTO tb_user (name, age) VALUES ('Alice', 25)")

    # 操作 3：更新数据
    # cursor.execute("UPDATE tb_user SET age = 26 WHERE name = 'Alice'")

    # 提交事务
    conn.commit()
    print("事务提交成功！")

except Exception as e:
    # 回滚事务
    conn.rollback()
    print(f"操作失败，已回滚: {e}")

finally:
    # 关闭游标和连接
    cursor.close()
    conn.close()